<?php

namespace Agent\Controller;

use Common\Controller\AgentbaseController;

class BenefitController extends AgentbaseController {

    private $hs_benefit_obj;

    function _initialize() {
        parent::_initialize();
        $this->hs_benefit_obj = new \HuoShu\Benefit();
    }
    
    public function set(){
        $allitems=$this->hs_benefit_obj->AgentGameList_single($_SESSION['agent_id'],0,0);
        $totalRows=count($allitems);
        $page=new \Think\Page($totalRows,15);
        $items=$this->hs_benefit_obj->AgentGameList_single($_SESSION['agent_id'],$page->firstRow,$page->listRows);
        $this->assign("items",$items);
        
        $selfagentname = M('users')->where(array("id"=>$_SESSION['agent_id']))->getField("user_login");
        $this->assign("selfagentname",$selfagentname);
        $this->assign("page",$page->show());
        $this->display();
    }
    
    public function get_default_agent_rate($agid){
        
        $hs_benefit_obj=new \HuoShu\Benefit();

        return $hs_benefit_obj->get_app_default_agentrate_by_agid($agid);
    }
    
    
    public function discount_filter($agent_rate,$mem_first,$mem_refill){
        
    }
    public function rebate_filter($agent_rate,$mem_first,$mem_refill){
        
    }
    public function set_sub(){
        $agid=I('agid');
        $benefit_type=I('benefit_type');        
        
        $data=array();
        
        $data['agent_rate']=I('agent_rate');
       
        $agent_rate=I('agent_rate');
        
        $default_agent_rate=$this->get_default_agent_rate($agid);
        if($default_agent_rate>$agent_rate){
            $this->ajaxReturn(array("error"=>"1","msg"=>"渠道折扣不能小于".$default_agent_rate));
            exit;
        }
        
        $this->set_rate_record($agid, $data,$benefit_type);
        
        $this->ajaxReturn(array("error"=>"0","msg"=>"设置成功"));
    }
    
    public function set_rate_record($agid,$data,$benefit_type){
        $exist=M('agent_game_rate')->where(array("ag_id"=>$agid))->find();
        if($exist){
            $data['update_time']=time();
            M('agent_game_rate')->where(array("ag_id"=>$agid))->save($data);
        }else{
            $data['ag_id']=$agid;
            
            
            $agent_id=M('agent_game')->where(array("id"=>$agid))->getField("agent_id");
            $app_id=M('agent_game')->where(array("id"=>$agid))->getField("app_id");
            
            $data['agent_id']=$agent_id;
            $data['app_id']=$app_id;
            
            
            $data['benefit_type']=$benefit_type;
            $data['create_time']=time();
            $data['update_time']=time();
            M('agent_game_rate')->add($data);
        }
    }
}
